/*
 * Copyright 1999-2011 Alibaba Group.
 *  
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *  
 *      http://www.apache.org/licenses/LICENSE-2.0
 *  
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.alibaba.dubbo.remoting.transport.netty;

import com.alibaba.dubbo.common.URL;
import com.alibaba.dubbo.common.utils.NetUtils;
import com.alibaba.dubbo.remoting.Channel;
import com.alibaba.dubbo.remoting.ChannelHandler;

import org.jboss.netty.channel.ChannelHandler.Sharable;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelHandler;

import java.net.InetSocketAddress;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * NettyHandler
 *
 * @see NettyHandler#messageReceived(ChannelHandlerContext, MessageEvent)
 * @author william.liangf
 */
@Sharable
public class NettyHandler extends SimpleChannelHandler {

    private final Map<String, Channel> channels = new ConcurrentHashMap<String, Channel>(); // <ip:port, channel>

    private final URL url;

    private final ChannelHandler handler;

    /**
     * netty处理器，主要实现了{@link NettyHandler#messageReceived}方法
     * @param url
     * @param handler 收到消息，具体实现是由hander对象来处理的。
     */
    public NettyHandler(URL url, ChannelHandler handler) {
        if (url == null) {
            throw new IllegalArgumentException("url == null");
        }
        if (handler == null) {
            throw new IllegalArgumentException("handler == null");
        }
        this.url = url;
        this.handler = handler;
    }

    public Map<String, Channel> getChannels() {
        return channels;
    }

    @Override
    public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
        NettyChannel channel = NettyChannel.getOrAddChannel(ctx.getChannel(), url, handler);
        try {
            if (channel != null) {
                channels.put(NetUtils.toAddressString((InetSocketAddress) ctx.getChannel().getRemoteAddress()), channel);
            }
            handler.connected(channel);
        } finally {
            NettyChannel.removeChannelIfDisconnected(ctx.getChannel());
        }
    }

    @Override
    public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
        NettyChannel channel = NettyChannel.getOrAddChannel(ctx.getChannel(), url, handler);
        try {
            channels.remove(NetUtils.toAddressString((InetSocketAddress) ctx.getChannel().getRemoteAddress()));
            handler.disconnected(channel);
        } finally {
            NettyChannel.removeChannelIfDisconnected(ctx.getChannel());
        }
    }

    /**
     * <pre>
     * 默认情况下 Dubbo 使用 Netty 作为底层的通信框架。
     * <b>Netty接收到消息之后，处理逻辑：</b>
     * 1、交给多消息处理器
     * 2、如果是心跳请求，则HeartbeatHandler心跳处理器，去处理心跳请求
     * 3、全消息派发器：把请求派发到线程池中
     *       在线程池中：
     * 4、消息解码decode
     * 5、HeaderExchangeHandler
     * 6、如果是方法调用，则交给DubboProtocol.requestHandler 这个【方法调用处理器】
     * 7、找到provider端的invoker代理类，进行方法调用，并返回结果。
     * NettyHandler#messageReceived(ChannelHandlerContext, MessageEvent)    -- netty框架，接收到消息会回调messageReceived() 方法
     *   -> AbstractPeer#received(Channel, Object)                          -- 可能是NettyServer，也可能是NettyClient的received() 方法
     *       -> MultiMessageHandler#received(Channel, Object)               -- 多消息处理器  （一次收到的消息可能有多条）
     *           -> HeartbeatHandler#received(Channel, Object)              -- 心跳处理器
     *               -> AllChannelHandler#received(Channel, Object)         -- 全消息派发器
     *                  -> ExecutorService#execute(Runnable)                -- 把处理消息的逻辑，派发到线程池，由线程池去处理
     *
     *                  线程池中-> ChannelEventRunnable#run() -> handler.received(channel, message);
     *                              -> DecodeHandler#received(Channel, Object) -> handler.received(channel, message);   -- 消息放到线程池中，需要险decode解码
     *                                  -> HeaderExchangeHandler#received(Channel channel, Object message)              -- 之后交给HeaderExchangeHandler
     *                                      -> this#handleRequest(ExchangeChannel, Request)
     *                                          -> DubboProtocol.requestHandler#reply(ExchangeChannel, Object)          -- 回答；回应；做出反应
     *                                              -> Filter#invoke(Invoker, Invocation)
     *                                                  -> AbstractProxyInvoker#invoke(Invocation)
     *                                                      -> Wrapper0#invokeMethod(Object, String, Class[], Object[])
     *                                                          -> DemoServiceImpl#sayHello(String)
     * </pre>
     * @param ctx
     * @param e
     * @throws Exception
     */
    @Override
    public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
        NettyChannel channel = NettyChannel.getOrAddChannel(ctx.getChannel(), url, handler);
        try {
            handler.received(channel, e.getMessage());
        } finally {
            NettyChannel.removeChannelIfDisconnected(ctx.getChannel());
        }
    }

    @Override
    public void writeRequested(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
        super.writeRequested(ctx, e);
        NettyChannel channel = NettyChannel.getOrAddChannel(ctx.getChannel(), url, handler);
        try {
            handler.sent(channel, e.getMessage());
        } finally {
            NettyChannel.removeChannelIfDisconnected(ctx.getChannel());
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {
        NettyChannel channel = NettyChannel.getOrAddChannel(ctx.getChannel(), url, handler);
        try {
            handler.caught(channel, e.getCause());
        } finally {
            NettyChannel.removeChannelIfDisconnected(ctx.getChannel());
        }
    }

}